﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
using ArbolandiaBL;

public partial class _Categories : Page
{
    String detailid = "";
    public Boolean hide = false;

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            LoadDetail();
            //drpCategories.SelectedIndexChanged += drpCategories_SelectedIndexChanged;
        }
        LoadBanners();
    }
    protected void LoadDetail()
    {
        try
        {
            detailid = Request.QueryString["d"]; if (string.IsNullOrEmpty(detailid)) { detailid = "30"; }

            if (detailid == null)
            {
                Response.Redirect("~/Default.aspx");
            }
            else
            {
                var service = new ServiceUI();
                var detail = service.GetProductDetail(Int32.Parse(detailid));

                if (detail == null)
                {
                    hide = true;
                    var tmp = service.GetProductVariousDetail(Int32.Parse(detailid));
                    detail = new UIProductDetail()
                    {
                        Complements = tmp.Complements,
                        Detalles = tmp.Detalles,
                        DiscountPrice = tmp.DiscountPrice,
                        Id = tmp.Id,
                        IsDestacado = tmp.IsDestacado,
                        IsOferta = tmp.IsOferta,
                        LongDescription = tmp.LongDescription,
                        Mantenimiento = "",
                        MesesFloracion = "",
                        MesesFrutos = "",
                        Name = tmp.Name,
                        Plantacion = "",
                        ScientistName = "",
                        ShortDescription = tmp.ShortDescription,
                        SubCategoryId = tmp.SubCategoryId
                    };
                    detail.ProductPriceDetails.AddRange(tmp.ProductPriceDetails.ToList());
                    detail.ThumbnailsImages.AddRange(tmp.ThumbnailsImages.ToList());
                    detail.FullSizeImages.AddRange(tmp.FullSizeImages.ToList());
                    detail.Complements.AddRange(tmp.Complements.ToList());
                }

                //Map
                var subcategory = service.GetSubCategoryDetail(detail.SubCategoryId);
                if (subcategory == null) { subcategory = NewUISubcategoryDetail.newSubcategoryDetail; }
                var category = service.GetCategorys().Where(x => x.Id == subcategory.IdCategory).FirstOrDefault<UICategoryResume>();
                if (category == null) { category = NewUICategoryResume.newCategoryResume; }
                var categories = service.GetCategorys();
                var subcategorieslist = new ServiceUI().GetSubcategorys(category.Id);

                //lblRoute.Text = "INICIO / " + category.Name.ToUpper() + " / " + subcategory.Name.ToUpper() + " / <span style='color:#9FB32B;'>" + detail.Name.ToUpper() + "</span>";
                lblRoute.Text = "INICIO / "; lblRoute.NavigateUrl = "Default.aspx";
                lblRoute1.Text = category.Name.ToUpper() + " / "; lblRoute1.NavigateUrl = "Categories.aspx?c=" + category.Id;
                lblRoute2.Text = subcategory.Name.ToUpper() + " / "; lblRoute2.NavigateUrl = "Subcategories.aspx?s=" + subcategory.Id;
                lblRoute3.Text = detail.Name.ToUpper();

                for (int i = 0; i < categories.Count(); i++)
                {
                    drpCategories.Items.Add(new ListItem(categories[i].Name, categories[i].Id.ToString()));
                    if (categories[i].Name.ToUpper() == category.Name.ToUpper())
                    {
                        drpCategories.Items[i + 1].Selected = true;
                    }
                }

                for (int i = 0; i < subcategorieslist.Count(); i++)
                {
                    //left banner
                    var div = new HtmlGenericControl("div");
                    var hl = new HyperLink();

                    if (subcategorieslist[i].Id.ToString() == detail.SubCategoryId.ToString())
                    {
                        hl.ForeColor = System.Drawing.Color.Red;
                    }

                    hl.ID = "sc_" + subcategorieslist[i].Id.ToString();
                    hl.Text = subcategorieslist[i].Name + " (" + subcategorieslist[i].TotalProducts + ")";
                    hl.NavigateUrl = "~/Subcategories.aspx?s=" + subcategorieslist[i].Id.ToString();
                    div.Controls.Add(hl);
                    subcategories.Controls.Add(div);
                }


                //Info
                productName.InnerText = detail.Name;
                productDescription.InnerText = detail.LongDescription;
                if (category.Id <= 2)
                {
                    productSize.InnerText = "Altura máxima: " + detail.Size + " mts";
                }
                scientificName.InnerText = detail.ScientistName;
                purchaseOptions.InnerText = "Opciones de compra";

                //SocialPlugins
                //var socialPlugin = GetSocialPlugInDiv(detail.Name, detail.ShortDescription, HttpContext.Current.Request.Url.AbsoluteUri);
                //socialPlugins.Controls.Add(socialPlugin);
                var imageLink = detail.FullSizeImages.Count() > 0 ? detail.FullSizeImages.First().ImageUrl : "";
                HtmlMeta ogTitle = new HtmlMeta() { };
                HtmlMeta meta = new HtmlMeta() { Name = "description", Content = detail.ShortDescription };
                HtmlMeta metaTitle = new HtmlMeta() { Name = "keywords", Content = detail.Name };
                HtmlLink linkImage = new HtmlLink() { };
                ogTitle.Attributes.Add("property", "og:title");
                ogTitle.Attributes.Add("content", detail.Name);
                linkImage.Attributes.Add("rel", "image_src");
                linkImage.Attributes.Add("href", imageLink);
                this.Page.Master.FindControl("metadata").Controls.Add(ogTitle);
                this.Page.Master.FindControl("metadata").Controls.Add(meta);
                this.Page.Master.FindControl("metadata").Controls.Add(metaTitle);
                this.Page.Master.FindControl("metadata").Controls.Add(linkImage);

                //Imágenes
                if (detail.FullSizeImages.Count() > 0)
                {
                    //productImage.ImageUrl = detail.FullSizeImages[0].ImageUrl;
                    for (int i = 0; i < detail.FullSizeImages.Count(); i++)
                    {
                        var c = new HyperLink() { ImageUrl = detail.FullSizeImages[i].ImageUrl, NavigateUrl = detail.FullSizeImages[i].LinkUrl };
                        //var p = new HyperLink() { NavigateUrl = detail.FullSizeImages[i].LinkUrl, Text = ((i + 1)).ToString() };
                        //c.Target = "_blank";
                        //p.Attributes.Add("rel", ((i + 1)).ToString());
                        imagereel_detail.Controls.Add(c);
                        //paging_detail.Controls.Add(p);
                    }
                    //}
                }

                //productos para comprar
                for (int i = 0; i < detail.ProductPriceDetails.Count(); i++)
                {
                    var div = new HtmlGenericControl("div");
                    div.Attributes.Add("class", "product-item");

                    var leftDiv = new HtmlGenericControl("div");
                    leftDiv.Attributes.Add("class", "p-left-div");

                    var code = new HtmlGenericControl("div");
                    code.InnerText = detail.ProductPriceDetails[i].ProductCode;
                    code.Attributes.Add("class", "product-code");
                    leftDiv.Controls.Add(code);

                    var descrip = new HtmlGenericControl("div");
                    descrip.InnerText = Truncate(detail.ProductPriceDetails[i].Description, 105);
                    descrip.Attributes.Add("class", "product-descrip");
                    leftDiv.Controls.Add(descrip);

                    var available = new HtmlGenericControl("div");
                    available.InnerText = (detail.ProductPriceDetails[i].Stock == 0 ? "No disponible" : "Disponible");
                    available.Attributes.Add("class", "product-available-" + (detail.ProductPriceDetails[i].Stock == 0 ? "red" : "green"));
                    leftDiv.Controls.Add(available);

                    leftDiv.Controls.Add(new HtmlGenericControl("br"));

                    var rightDiv = new HtmlGenericControl("div");
                    rightDiv.Attributes.Add("class", "p-right-div");

                    var price = new HtmlGenericControl("div");
                    price.InnerText = detail.ProductPriceDetails[i].Price.ToString("C") + " pesos";
                    price.Attributes.Add("class", "product-price");
                    rightDiv.Controls.Add(price);

                    var quantity = new HtmlGenericControl("div");
                    quantity.InnerText = "Cantidad ";
                    quantity.Attributes.Add("class", "product-quantity");

                    var input = new TextBox();
                    input.CssClass = "product-input";
                    input.MaxLength = 4;
                    input.ID = "txt_" + detail.ProductPriceDetails[i].Id;
                    quantity.Controls.Add(input);

                    //quantity.Controls.Add(new LiteralControl(" de " + detail.ProductPriceDetails[i].Stock.ToString()));
                    rightDiv.Controls.Add(quantity);

                    var addcart = new HtmlGenericControl("div");
                    addcart.Attributes.Add("class", "product-cart");

                    var hlcart = new LinkButton();
                    hlcart.Text = "Añadir al carrito";
                    hlcart.ID = "add_" + detail.ProductPriceDetails[i].Id;
                    hlcart.OnClientClick = "add(" + detail.Id + "," + detail.ProductPriceDetails[i].Id + ", document.getElementById(\"ContentPlaceHolder1_" + input.ClientID + "\").value); return false;";
                    addcart.Controls.Add(hlcart);

                    var cartimage = new Image();
                    cartimage.ImageUrl = "~/Images/carrito.png";
                    addcart.Controls.Add(cartimage);
                    rightDiv.Controls.Add(addcart);


                    div.Controls.Add(leftDiv);
                    div.Controls.Add(rightDiv);

                    productsList.Controls.Add(div);

                }

                //floracion
                var floracion = detail.MesesFloracion.Split(',');
                if (floracion.Count() > 0 && floracion[0] != "")
                {
                    foreach (var f in floracion)
                    {
                        switch (Int32.Parse(f))
                        {
                            case 1: floracionEne.Attributes.Add("style", "background-color: #FF9B24;"); break;
                            case 2: floracionFeb.Attributes.Add("style", "background-color: #FF9B24;"); break;
                            case 3: floracionMar.Attributes.Add("style", "background-color: #FF9B24;"); break;
                            case 4: floracionAbr.Attributes.Add("style", "background-color: #FF9B24;"); break;
                            case 5: floracionMay.Attributes.Add("style", "background-color: #FF9B24;"); break;
                            case 6: floracionJun.Attributes.Add("style", "background-color: #FF9B24;"); break;
                            case 7: floracionJul.Attributes.Add("style", "background-color: #FF9B24;"); break;
                            case 8: floracionAgo.Attributes.Add("style", "background-color: #FF9B24;"); break;
                            case 9: floracionSep.Attributes.Add("style", "background-color: #FF9B24;"); break;
                            case 10: floracionOct.Attributes.Add("style", "background-color: #FF9B24;"); break;
                            case 11: floracionNov.Attributes.Add("style", "background-color: #FF9B24;"); break;
                            case 12: floracionDiv.Attributes.Add("style", "background-color: #FF9B24;"); break;
                        }
                    }
                }
                else
                {
                    monthsFloracion.Attributes.Add("style", "display: none !important;");
                }

                //frutos
                var frutos = detail.MesesFrutos.Split(',');
                if (frutos.Count() > 0 && frutos[0] != "")
                {
                    foreach (var f in frutos)
                    {
                        switch (Int32.Parse(f))
                        {
                            case 1: frutosEne.Attributes.Add("style", "background-color: #F62828;"); break;
                            case 2: frutosFeb.Attributes.Add("style", "background-color: #F62828;"); break;
                            case 3: frutosMar.Attributes.Add("style", "background-color: #F62828;"); break;
                            case 4: frutosAbr.Attributes.Add("style", "background-color: #F62828;"); break;
                            case 5: frutosMay.Attributes.Add("style", "background-color: #F62828;"); break;
                            case 6: frutosJun.Attributes.Add("style", "background-color: #F62828;"); break;
                            case 7: frutosJul.Attributes.Add("style", "background-color: #F62828;"); break;
                            case 8: frutosAgo.Attributes.Add("style", "background-color: #F62828;"); break;
                            case 9: frutosSep.Attributes.Add("style", "background-color: #F62828;"); break;
                            case 10: frutosOct.Attributes.Add("style", "background-color: #F62828;"); break;
                            case 11: frutosNov.Attributes.Add("style", "background-color: #F62828;"); break;
                            case 12: frutosDiv.Attributes.Add("style", "background-color: #F62828;"); break;
                        }
                    }
                }
                else
                {
                    monthsFrutos.Attributes.Add("style", "display: none !important;");
                }

                //preferences
                int max = 99;
                for (int j = 0; j < detail.Preferences.Count; j++)
                {
                    if (j >= max) { break; }
                    var prefImg = new Image();
                    prefImg.CssClass = "product-preferencias-imgs-right";
                    //prefImg.ImageUrl = "http://dataclinicc.web709.discountasp.net/arb/imagessite/notavaible.jpg";
                    prefImg.ImageUrl = detail.Preferences[j].ImageUrl;
                    prefImg.ToolTip = string.IsNullOrEmpty(detail.Preferences[j].Description) ? detail.Preferences[j].Name : detail.Preferences[j].Description;
                    preferencesList.Controls.Add(prefImg);

                }
                if (detail.Preferences.Count() <= 0)
                {
                    Div1.Attributes.Add("style", "display: none !important;");
                }

                //tabs
                plantacionText.InnerHtml = detail.Plantacion;
                mantenimientoText.InnerHtml = detail.Mantenimiento;
                detallesText.InnerHtml = detail.Detalles;

                //hidetabs for  various detail
                if (hide)
                {
                    //Hide Mantenimiento tab and div
                    mantenimientoTab.Style.Remove(HtmlTextWriterStyle.Display);
                    mantenimientoTab.Style.Add(HtmlTextWriterStyle.Display, "none");
                    mantenimientoText.Style.Remove(HtmlTextWriterStyle.Display);
                    mantenimientoText.Style.Add(HtmlTextWriterStyle.Display, "none");
                    mantenimientoText.Attributes["class"] = "unselected-tab";
                    //Hide plantacion tab and div
                    plantacionTab.Style.Remove(HtmlTextWriterStyle.Display);
                    plantacionTab.Style.Add(HtmlTextWriterStyle.Display, "none");
                    plantacionText.Style.Remove(HtmlTextWriterStyle.Display);
                    plantacionText.Style.Add(HtmlTextWriterStyle.Display, "none");
                    plantacionText.Attributes["class"] = "unselected-tab";
                    //Select Detalle tab make it visible
                    detallesTab.Style.Remove(HtmlTextWriterStyle.Display);
                    detallesTab.Style.Add(HtmlTextWriterStyle.Display, "block");
                    detallesText.Style.Remove(HtmlTextWriterStyle.Display);
                    detallesText.Style.Add(HtmlTextWriterStyle.Display, "block");
                    detallesTab.Attributes["class"] = "selected-tab";
                }

                //related products
                var related = detail.Complements;
                for (int i = 0; i < related.Count(); i++)
                {
                    //Main container
                    var item = new HtmlGenericControl("div");
                    if (i == 3 || i == 7 || i == 11 || i == 15 || i == 19 || i == 23 || i == 27 || i == 31)
                    {
                        item.Attributes.Add("class", "list-item-right");
                    }
                    else
                    {
                        item.Attributes.Add("class", "list-item");
                    }

                    //Control for link
                    var link = new HyperLink();
                    link.NavigateUrl = "~/Detail.aspx?d=" + related[i].Id;

                    //Main image
                    var img = new Image();
                    img.ImageUrl = related[i].ImageUrl;
                    img.CssClass = "list-item-image";

                    //Product name and lower price
                    var info = new HtmlGenericControl("div");
                    info.Attributes.Add("class", "list-item-info");

                    var infotext = new HtmlGenericControl("div");
                    infotext.Attributes.Add("class", "list-item-info-text");

                    var infotextproductname = new Label();
                    infotextproductname.CssClass = "list-item-info-text-product";
                    infotextproductname.Text = related[i].Name;

                    var infotextlowerprice = new Label();
                    infotextlowerprice.CssClass = "list-item-info-text-lower";
                    infotextlowerprice.Text = "Desde " + related[i].LowerPrice.ToString("C") + " pesos";

                    var cartimage = new Image();
                    cartimage.Attributes.Add("class", "list-item-text-cart");
                    cartimage.ImageUrl = "~/Images/carrito.png";

                    infotext.Controls.Add(infotextproductname);
                    infotext.Controls.Add(infotextlowerprice);
                    info.Controls.Add(infotext);
                    //info.Controls.Add(cartimage);
                    info.Controls.Add(new HtmlGenericControl("br"));
                    link.Controls.Add(img);
                    link.Controls.Add(info);
                    item.Controls.Add(link);
                    homeOffers.Controls.Add(item);
                }
                if (related.Count() <= 0)
                {
                    lblHomeOfferProductsTitle.Visible = false;
                }

                homeOffers.Controls.Add(new HtmlGenericControl("br"));


            }
        }
        catch (Exception ex)
        {


        }

    }
    protected HtmlGenericControl GetSocialPlugInDiv(string title, string summary, string url)
    {

        var c = new HtmlGenericControl("div");
        //c.ID = Guid.NewGuid().ToString().Replace("-", "");
        c.Attributes.Add("class", "addthis_toolbox addthis_default_style addthis_32x32_style");
        c.Attributes.Add("addthis:url", url);
        c.Attributes.Add("addthis:title", title);
        c.Attributes.Add("addthis:description", summary);
        //c.Style.Add(HtmlTextWriterStyle.TextAlign, "right");

        //Facebook
        var s = new HtmlGenericControl("a");
        s.Attributes.Add("class", "addthis_button_preferred_1");
        c.Controls.Add(s);
        //gmail
        var s1 = new HtmlGenericControl("a");
        s1.Attributes.Add("class", "addthis_button_preferred_2");
        c.Controls.Add(s1);
        //twitter
        var s2 = new HtmlGenericControl("a");
        s2.Attributes.Add("class", "addthis_button_preferred_3");
        c.Controls.Add(s2);
        //googleplus
        var s3 = new HtmlGenericControl("a");
        s3.Attributes.Add("class", "addthis_button_google_plusone");
        c.Controls.Add(s3);
        return c;
    }
    public static string Truncate(string source, int length)
    {
        if (source.Length > length)
        {
            source = source.Substring(0, length);
        }
        return source;
    }
    public void pageNumberClick(object sender, EventArgs e)
    {
        try
        {

        }
        catch (Exception)
        {
            throw;
        }
    }

    protected void drpCategories_SelectedIndexChanged(object sender, EventArgs e)
    {
        Response.Redirect("~/Categories.aspx?c=" + ((DropDownList)sender).SelectedValue.ToString());
    }

    protected void LoadBanners()
    {
        try
        {
            var banner1 = new ServiceUI().GetBanner(BannerType.Top);
            for (int i = 0; i < banner1.Count(); i++)
            {
                var c = new HyperLink() { ImageUrl = banner1[i].Url, NavigateUrl = banner1[i].LinkUrl };
                var p = new HyperLink() { NavigateUrl = banner1[i].LinkUrl, Text = ((i + 1)).ToString() };
                c.Target = "_blank";
                p.Attributes.Add("rel", ((i + 1)).ToString());
                imagereel.Controls.Add(c);
                paging.Controls.Add(p);
            }
            var banner2 = new ServiceUI().GetBanner(BannerType.Middle);
            for (int i = 0; i < banner2.Count(); i++)
            {
                var c = new HyperLink() { ImageUrl = banner2[i].Url, NavigateUrl = banner2[i].LinkUrl };
                var p = new HyperLink() { NavigateUrl = banner2[i].LinkUrl, Text = ((i + 1)).ToString() };
                c.Target = "_blank";
                p.Attributes.Add("rel", ((i + 1)).ToString());
                imagereel2.Controls.Add(c);
                paging2.Controls.Add(p);
            }
            var banner3 = new ServiceUI().GetBanner(BannerType.Bottom);
            for (int i = 0; i < banner3.Count(); i++)
            {
                var c = new HyperLink() { ImageUrl = banner3[i].Url, NavigateUrl = banner3[i].LinkUrl };
                var p = new HyperLink() { NavigateUrl = banner3[i].LinkUrl, Text = ((i + 1)).ToString() };
                c.Target = "_blank";
                p.Attributes.Add("rel", ((i + 1)).ToString());
                imagereel3.Controls.Add(c);
                paging3.Controls.Add(p);
            }
        }
        catch (Exception)
        {


        }

    }

    [System.Web.Services.WebMethod(true)]
    public static Int32 Add(Int32 detailid, Int32 productid, Int32 quantity)
    {
        try
        {
            if (HttpContext.Current.Session["arbolandiacart"] == null)
            {
                HttpContext.Current.Session["arbolandiacart"] = new List<String>();
            }

            ((List<String>)HttpContext.Current.Session["arbolandiacart"]).Add(detailid.ToString() + "|" + productid.ToString() + "|" + quantity.ToString());

            return ((List<String>)HttpContext.Current.Session["arbolandiacart"]).Count();
        }
        catch (Exception)
        {
            return -1;
        }
    }
}